package com.dream.service.recommender.edm;

import com.alibaba.fastjson.JSONObject;
import com.dream.common.toolkits.clickstream.HttpClientUtils;
import com.dream.common.toolkits.json.JsonUtils;
import com.dream.service.recommender.edm.config.EDMConfig;
import com.dream.service.recommender.edm.enums.DeployType;
import com.dream.service.recommender.edm.enums.EDMType;
import com.dream.service.recommender.domain.response.RecommenderData;
import com.dream.service.recommender.domain.response.RecommenderSku;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * Created by kangd on 2016/9/26.
 */
public class EDMResult {

    public static RecommenderData<RecommenderSku> getCouponEDMRecommender(EDMType edmType, String uuid, String pin, int limit, DeployType deployType){
        return getEDMRecommender(edmType,new Object[]{deployType.getDomain(),limit,uuid,pin});
    }

    public static RecommenderData<RecommenderSku> getEDMRecommender(EDMType edmType,Object[] objects){
        try{
            String url = UriComponentsBuilder.fromHttpUrl(edmType.getEdmURL()).buildAndExpand(objects).toUriString();
            String jsonStr = HttpClientUtils.getDataFromUri(url, EDMConfig.ENCODE);
            RecommenderData<RecommenderSku> recommender=null;
            if(StringUtils.isNotEmpty(jsonStr) && !jsonStr.equals("ERROR") && JSONObject.parseObject(jsonStr).getBoolean("success") !=null
                    && JSONObject.parseObject(jsonStr).getBoolean("success") &&
                    JSONObject.parseObject(jsonStr).getInteger("code") !=null &&
                    JSONObject.parseObject(jsonStr).getInteger("code") == 0 &&
                    JSONObject.parseObject(jsonStr).getJSONObject("data") !=null){
                recommender = JsonUtils.fromJson(JSONObject.parseObject(jsonStr).getJSONObject("data").toJSONString(), new TypeToken<RecommenderData<RecommenderSku>>() {
                }.getType());
                if(recommender==null || recommender.getList()==null || recommender.getList().size()==0){
                    return null;
                }
            }
            return recommender;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
